package org.irri.smta.ui.bean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;

import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.irri.smta.common.Constants;
import org.irri.smta.domain.ReportLog;
import org.irri.smta.service.IReportLogService;
import org.irri.smta.util.BeanUtils;
import org.primefaces.event.FileUploadEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Named("templateUploadBean")
@ViewScoped
public class TemplateUploadBean implements Serializable {

	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = LoggerFactory
			.getLogger(TemplateUploadBean.class);

	@Inject
	@Named("resourceConfigBean")
	private ResourceConfigBean resourceConfigBean;

	@Inject
	@Named("reportLogService")
	private IReportLogService<ReportLog, Long> reportLogService;

	private BeanUtils beanUtils = new BeanUtils();

	public void uploadSmtaTemplate(FileUploadEvent event) {
		LOGGER.info("uploadSmtaTemplate(FileUploadEvent event)" + event);
		String templateDirectory = resourceConfigBean
				.getSmtaTemplateDirectory();
		String templateFilename = resourceConfigBean.getSmtaTemplateFilename() + Constants.TEMPLATE_EXTENSION;
		handleFileUpload(event, templateDirectory, templateFilename);
	}

	public void uploadMtaTemplate(FileUploadEvent event) {
		LOGGER.info("uploadOmtaTemplate(FileUploadEvent event)" + event);
		String templateDirectory = resourceConfigBean
				.getMtaTemplateDirectory();
		//String templateFilename = resourceConfigBean.getMtaTemplateFilename();
		String templateFilename = event.getFile().getFileName();
		handleFileUpload(event, templateDirectory, templateFilename);
	}

	public void handleFileUpload(FileUploadEvent event, String directory,
			String filename) {
		LOGGER.info("handleFileUpload(FileUploadEvent event, String directory, String filename)"
				+ event);
		try {
			InputStream inputStream = event.getFile().getInputstream();
			OutputStream out = new FileOutputStream(new File(directory,
					filename));
			int read = 0;
			byte[] bytes = new byte[1024];

			while ((read = inputStream.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
			inputStream.close();
			out.flush();
			out.close();
			beanUtils.updateInfoMessage("Template Upload Successful",
					"Template sucessfully uploaded.");
		} catch (IOException e) {
			// Add exception to report log
			reportLogService.addReportLog(e.getMessage());
			beanUtils.updateInfoMessage("Template Upload Failed",
					"Unable to upload template. " + e.getMessage());
			LOGGER.error(e.getMessage());
		}
	}

}
